var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app=getApp()
const citys = [ // 我们习惯的格式。 可以后台给你出，如果你打不过的话，你就。。。
  {
   text: "测试一", // 默认识别text标签
   id: 1,
   children: [
    {
     id: 11,
     text: "测试1-1",
     children: [
      {
       id: 111,
       text: "测试1-1-1"
      },
      {
       id: 112,
       text: "测试1-1-2"
      }
     ]
    },
    {
     id: 12,
     text: "测试1-2",
     children: [
      {
       id: 122,
       text: "测试1-2-1"
      },
      {
       id: 122,
       text: "测试1-2-2"
      }
     ]
    },
    {
     id: 13,
     text: "测试1-3"
    }
   ]
  },
  {
   text: "测试二",
   id: 2,
   children: [
    {
     id: 21,
     text: "测试2",
     children: [
      {
       id: 221,
       text: "测试2-2-1"
      },
      {
       id: 222,
       text: "测试2-2-2"
      }
     ]
    },
    {
     id: 22,
     text: "测试2"
    },
    {
     id: 23,
     text: "测试2"
    }
   ]
  },
  {
   text: "测试三",
   id: 3,
   children: [
    {
     id: 31,
     text: "测试3",
     children: [
      {
       id: 311,
       text: "测试3-1-1"
      },
      {
       id: 312,
       text: "测试3-3-2"
      }
     ]
    },
    {
     id: 32,
     text: "测试3"
    },
    {
     id: 33,
     text: "测试3"
    }
   ]
  }
 ];
//获取应用实例
// const app = getApp()
Page({
  data: {
    flag_integral:false,
    integral:0,
    phone:'',
    useraddress:'',
    // 优惠卷
    coupon:'',
    value:"",
    // 当前等待的人数
    waitpeople:0,
    shopeat:0,
    outeat:0,
    // 设置店铺
    selectshop:'',
    // 取餐码
    getcode:'0002',

    columns:[{
           values: citys, // 设置的页面初始值
           className: "column1"
          },
          {
           values: citys[0].children,
           className: "column2"
          },
          {
           values: citys[0].children[0].children,
           className: "column3"
          }],
    // 时间选择器
    relWkibedat:'',
    // 弹出层显示
    show: false,
    // 统计商品数量和价格
    orderCount: {
      num: 0,
      money: 0
    },
    bottomFlag: false,
    // 提交的订单
    orders: true,
    items: [],
    // 时间
    currentDate: new Date().getHours() + ':' + (new Date().getMinutes() % 10 === 0 ? new Date().getMinutes() : Math.ceil(new Date().getMinutes() / 10) * 10),
    minHour: new Date().getHours(),
    minMinute: new Date().getMinutes(),
    formatter(type, value) {
      if (type === 'hour') {
        return `${value}点`;
      } else if (type === 'minute') {
        return `${value}分`;
      }
      return value;
    },
    filter(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 10 === 0);
      }
      return options;
    },

  },
  // 点击对应菜单添加按钮
  del: function (event) {
    let that = this;
    let id = event.target.dataset.id;
    let index = event.target.dataset.index;
    let param = this.data.items[index];
    
    if(param.nums > 0){
      param.nums--; // 每点一次减少1
    } else {
      param.nums = 0; // 最低为0
    }
    // 改变添加按钮的状态
    this.data.items.splice(index, 1, param);
    that.setData({
      items: this.data.items
    });
    let money = 0;
    let num = 0;
    // 将已经确定总价格和数量求和
    this.data.items.forEach(item => {
      money += item.price * item.nums;
      num += item.nums;
    });
    let orderCount = {
      num,
      money
    }
    // 设置显示对应的总数和全部价钱
    this.setData({
      orderCount:orderCount
    });
  },
  // 点击对应菜单添加按钮
  add: function(event) {
    let that = this;
    let id = event.target.dataset.id;
    let index = event.target.dataset.index;
    let param = this.data.items[index];
    let subOrders = []; // 购物单列表存储数据
    param.nums++; // 每点一次增加1
    // 改变添加按钮的状态
    console.log(param);
    this.data.items.splice(index, 1, param);
    that.setData({
      items: this.data.items
    });
    let money = 0;
    let num = 0;
    // 将已经确定总价格和数量求和
    this.data.items.forEach(item => {
      money += item.price*item.nums;
      num += item.nums; 
    });
    let orderCount = {
      num,
      money
    }
    // 设置显示对应的总数和全部价钱
    this.setData({
      orderCount
    });
  },
  // 点击结账按钮
  pay: function() {
    let that = this;
    let str = '选中' + that.data.orderCount.num + '件商品，共' + that.data.orderCount.money + '元，是否要支付？'
    wx.showModal({
      title: '提示',
      content: str,
      success: function (res) {
        // 至少选中一个商品才能支付
        if (that.data.orderCount.num !== 0){
          if (res.confirm) {
            wx.redirectTo({
              url: '../../pages/pay/pay'
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        } else {
          wx.showToast({
            title: '您未选中任何商品',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  onLoad: function() {
    // 取出订单传过来的数据
    let item = wx.getStorageSync('subOrders');
    this.setData({items: item});
     // 价格统计汇总
     let money = 0;
     let num = 0;
     this.data.items.forEach(item => {
       money += (item.good_price*item.number);
        // 总价格求和
        num += item.number;
     });
     let orderCount = {
       num,
       money
     }
     // 设置显示对应的总数和全部价钱
     this.setData({
       orderCount:orderCount
     });
    //  this.selectshop();
    let outeat=  wx.getStorageSync('outeat') ==1?1:0
    let shopeat=  wx.getStorageSync('shopeat') ==1?1:0
    if(outeat==0 && shopeat==0){
      outeat=1;
    }
    this.setData({
      outeat:outeat,
      shopeat:shopeat
    })

  },
  onShow(){
    let wxuuid=util.wxuuid();
    let uuid=wxuuid.slice(32);
    let userInfo=wx.getStorageSync('userInfo');
    let integral=userInfo.integral;
    this.setData({
      integral:integral,
      getcode:uuid
    })
    let shop=wx.getStorageSync('selectshop')[0];
    if(!shop){
      wx.setStorageSync('toselectshop', 'toselectshop')
      wx.showToast({
        title: '请选择店家位置',
        icon: 'error',
        duration: 2000,
        success:function(){
          wx.navigateTo({
            url: '/pages/index/map/map',
          });
        },
      })
    }else{
      this.selectshop();
    }

    let coupon=wx.getStorageSync('usecouon')[0];
    let orders=this.data.orderCount;
    console.log('coupon',coupon);
    if(coupon){
      if(orders.money>=coupon.minmoney){
        console.log('orders.money-coupon.type_money:',orders.money-coupon.submoney);
        orders.money=orders.money-coupon.submoney
      }
      console.log('xiugai:',orders)
      let content='满'+coupon.minmoney+'优惠了！'+'立减'+coupon.submoney+'元';
      
      this.setData({
        orderCount:orders,
        coupon:content
      });
    }
    let useraddress=wx.getStorageSync('selectaddress')[0]
    if(useraddress){
      this.setData({
        useraddress:useraddress.address
      })
    }
    let flag_integral;
      if(integral>30&&orders.money>20){
        orders.money=orders.money-2
        flag_integral=true
      }
      this.setData({
        flag_integral:flag_integral,
        orderCount:orders,
      })
    
  },
  showPopup(){
    console.log(1)
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  // 时间选择
  onConfirm(value) {
    const compact = arr => arr.filter(Boolean); // 三级联动 去除没值的，比如只有两级
    const result = compact(value);
    let str = ""; // 呈现页面显示 /xxx/xxx/xxx
    result.forEach(item => {
     str += "/" + item.text;
    });
    this.station = str;
    this.showPicker = false;
     
   const end = result[result.length - 1]; // 一般都是取最后一个id给后台的
    const id = end.id;
    console.log(id);
   },
   onChange(picker, values, index) { // 实在不行自己打印测试
    if (index == 0) {
     picker.setColumnValues(2, []); // 防止突然选中第一个，第二个是更新的，但第三个联级不更新，我暂时强制清空
    }
    let ColumnIndex = picker.getColumnIndex(index);
    console.log("第" + index + "列", "第" + ColumnIndex + "个");
    picker.setColumnValues(index + 1, values[ColumnIndex ].children || []);//点当前列更新下一列数据，防止undefined 
     
  // 当然，如果后台数据不给你想要的格式，你就按需请求一次了，比如选中第一个，取id请求接口，更新下一列。毕竟连动内容多的话，页面请求也多。但页面就不流畅，比如第一列第二列初始值。 
   // 我就是打不过后台。。。
   },
  //  获取备注的信息
   onChanges(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
  },
  // 提交订单
  toorders(event){
    console.log(event.currentTarget.dataset.price)
    let money=event.currentTarget.dataset.price;
    let orders=wx.getStorageSync('subOrders');
    console.log('orders:',orders)
    wx.setStorageSync('orders', orders)
    let id=orders[0].id
    console.log('id:',id)
    // 判断是不是使用了积分
    let flag_integral=this.data.flag_integral;
    // 想后台添加订单
    let wxuuorderid=util.wxuuid()
    let outeat=this.data.outeat
    let shopeat=this.data.shopeat;
    let getcode=this.data.getcode;
    let phone=this.data.phone;
    // console.log()
    let send_type=0;
    if(outeat==1){
      send_type=1
    }else{
      send_type=0
    }
    let shop=wx.getStorageSync('selectshop')[0];
    console.log('send_type:',send_type)
    if(!shop){
      wx.showModal({
        title:'提示',
        content:'请选择店家位置'
      })
      return false;
    }
    // util.request(api.OrderSubmit,{
      if(send_type==1){
        if(wx.getStorageSync('selectaddress')[0]==undefined){
          wx.showModal({
            title:'提示',
            content:'请选择收货地址'
          })
          return false;
        }
        if(phone.length==0){
          wx.showModal({
            title:'提示',
            content:'请输入手机号'
          })
          return false;
        }
        if (!/^1[3456789]\d{9}$/.test(phone)) {
          wx.showToast({
            title: '手机号格式有误',
            icon: 'none',
          });
          return false;
        }
        let coupon_sn=wx.getStorageSync('usecouon');
        if(coupon_sn){
          coupon_sn=coupon_sn[0].coupon_sn;
        }else{
          coupon_sn='0'
        }
        let useraddress=wx.getStorageSync('selectaddress')[0];
        util.request(api.AddOrders,{
          shop:shop.title,
          flag_integral:flag_integral,
          coupon_sn:coupon_sn,
          openid:wx.getStorageSync('openid'),
          order_sn:wxuuorderid,
          order:orders,
          totalmoney:money,
          send_type:send_type,
          code:getcode,
          addressid:useraddress.id
          // 添加收货地址id
        },"POST").then(res=>{
          // 存储订单号
          console.log('res:',res)
          let order_sn=res.order_sn;
          wx.setStorageSync('order_sn', order_sn)
        })
      }else{
        let coupon_sn=wx.getStorageSync('usecouon');
        if(coupon_sn){
          coupon_sn=coupon_sn[0].coupon_sn;
        }else{
          coupon_sn='0'
        }
        util.request(api.AddOrders,{
          shop:shop.title,
          flag_integral:flag_integral,
          coupon_sn:coupon_sn,
          openid:wx.getStorageSync('openid'),
          order_sn:wxuuorderid,
          order:orders,
          totalmoney:money,
          send_type:send_type,
          code:getcode,
          addressid:-1
          // 添加收货地址id
        },"POST").then(res=>{
          // 存储订单号
          console.log('res:',res)
          let order_sn=res.order_sn;
          wx.setStorageSync('order_sn', order_sn)
        })
      }
      
    // util.request(api.CartDelete,{
      for (let i = 0; i < orders.length; i++) {
        util.request(api.DelCarts,{
          id:orders[i]['id'],
         },"POST").then(res=>{
           console.log('res',res)
         })
      }
      
    wx.setStorageSync('subOrders', "")
   
    // wx.showModal({
    //   title: '支付订单哟',
    //   content: '你确定要支付'+money+'元吗？',
    //   success: function(res) {
    //    if (res.confirm) {
    //       wx.switchTab({
    //         url: '/pages/order/order/order',
    //       })
    //    }else{
    //     console.log(res);
    //     wx.switchTab({
    //       url: '/pages/order/order/order',
    //     })
         
    //    }
    //   }
    //  })
    // 核销缓存里面的优惠卷
    
    // 删除后端uercoupon列表里面的优惠卷
    let coupon_sn=wx.getStorageSync('usecouon');
    if(coupon_sn){
      coupon_sn=coupon_sn[0].coupon_sn;
    util.request(api.DelUserCoupon,{
      openid:wx.getStorageSync('openid'),
      coupon_sn:coupon_sn
    },'POST').then(res=>{
     let msg=res.msg;
     wx.showToast({
      title: msg,
      icon: 'success',
      duration: 2000,
      success:function(){
        wx.setStorageSync('usecouon', '')
        setTimeout(function () {
          //要延时执行的代码
          
          wx.reLaunch({
            url: '/pages/order/pay/pay',
          })
        }, 1000) //延迟时间
      },
    })
    })
    }else{
      wx.setStorageSync('usecouon', '')
      wx.reLaunch({
        url: '/pages/order/pay/pay',
      })
    }
   
  },
  // 自取
  shopeat(){
  
    this.setData({
      shopeat:1,
      outeat:0
    })
    console.log(this.data.shopeat)
    console.log(this.data.outeat)
  },
  // 外卖
  outeat(){
    this.setData({
      shopeat:0,
      outeat:1
    })
  },
  // 配送时间
  diningTimeChange(a) {
    const selectedHour = a.detail.getColumnValue(0).replace('点', '') * 1
    if (selectedHour == new Date().getHours()) {
      let minMinute = new Date().getMinutes()
      if (minMinute % 10 !== 0) {
        minMinute = minMinute / 10 + 1
      }
      this.setData({
        minMinute
      })
    } else {
      this.setData({
        minMinute: 0
      })
    }
  },
  diningTimeShow() {
    this.setData({
      diningTimeShow: true
    })
  },
  diningTimeHide() {
    this.setData({
      diningTimeShow: false
    })
  },
  diningTimeConfirm(e) {
    this.setData({
      diningTime: e.detail
    })
    this.diningTimeHide()
  },
// 设置店家位置
  selectshop(){
    let shop=wx.getStorageSync('selectshop')[0];
    // let
    // console.log('shop:',shop);
    this.setData({
      selectshop:shop.title
    })
  },
  // 选择店家
  toselectshop(){
    wx.setStorageSync('toselectorder', 'toselectorder');
    wx.navigateTo({
      url: '/pages/index/map/map',
    });
  },
  selectaddress(){
    wx.setStorageSync('toselectaddress', 'toselectaddress');
    wx.navigateTo({
      url: '/pages/me/address/address',
    });
  },
  // 选择优惠卷
  toselectcoupon(e){
    let money=e.currentTarget.dataset.summoney;
    wx.setStorageSync('toselectcoupon', money)
    wx.navigateTo({
      url: '/pages/me/coupon/coupon',
    })
  },
  onphoto(e){
    console.log('e:',e)
    console.log(e.detail);
    let phone=e.detail;
    this.setData({
      phone:phone
    })
  }
})